/*
* @Author: 丁
* @Date: 2024-11-27 09:15:50
* @LastEditors: white_queen
* @LastEditTime: 2024-12-06 17:42:22
* @FilePath: /config/request.js
* @Description: In User Settings Edit
*/

// var app_info=''
// import app_info from './index.js';
import app_info from "./index.js"
 const BASE_URL = app_info.api_host;
const version = app_info.version
const getData = (key, is_clear = false) => {
    var value = uni.getStorageSync(key);
    if (is_clear) {
        uni.setStorageSync(key, '');
    }
    return value;
}

/**
 * rich-text富文本中图片宽度最大100%
 * @param {String} html
 */
function formatRichText(html) {
	// 去掉img标签里的style、width、height属性
	let content_data = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
		return match
	})

	// 修改所有style里的width属性为max-width:100%
	content_data = content_data.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
		return match
	})

	// 去掉<br/>标签
	content_data = content_data.replace(/<br[^>]*\/>/gi, '')
	// img标签添加style属性：max-width:100%;height:auto
	content_data = content_data.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"')

	return content_data
}

/**
 * 获取已选科目ID
 */
function getSubjectId() {
	let user_subject = uni.getStorageSync('user_subject')
	if (user_subject && user_subject.subject2 && user_subject.subject2.id) {
		return user_subject.subject2.id
	}
	return 0
}
export function request(config = {}) {
	let {
		url,
		data = {},
		method = "GET",
		header = {},
		showLoading = true,
		isShowTip=true
	} = config
	url = BASE_URL + url

	header['content-type'] = "application/json"
	header['token'] = getData('token')
	header['app-version'] = version

	let timestamp = Date.parse(new Date())
	if (typeof(data) == 'object') {
		data['timestamp'] = timestamp
	}

	if (showLoading) {
		uni.showLoading({
			title: '加载中..',
			mask: true
		})
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data,
			method,
			header,
			success: res => {
				if (res.statusCode == 200) {
					if (res.data.code == 0) {
						if (isShowTip) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
					resolve(res.data)
				} else {
					console.log('http statusCode', res.statusCode)
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					// 未登录
					if (res.statusCode == 401) {

							uni.navigateTo({
								url: '/pages/user/login-reg'
							})
					}
					reject(res)
				}
			},
			fail: err => {
				reject(err)
			},
			complete: (res) => {
				showLoading && uni.hideLoading()
			}
		})
	})
}


/**
 * 上传文件
 * @returns {Promise<*>}
 */
export function uploadFile(handler, filePath, data = {}, fileType = 'image', showLoading = true) {
	if (showLoading) {
		uni.showLoading({
			title: '加载中..',
			mask: true
		})
	}

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: api_prefix + 'common/upload',
			header: {
				'token': uni.getStorageSync('token'),
				"Content-Type": "multipart/form-data"
			},
			fileType: fileType,
			filePath: filePath,
			formData: data,
			name: 'file',
			success: (res) => {
				console.log('upload res', res)
				let data = JSON.parse(res.data)
				if (res.statusCode == 200) {
					resolve(data)
				} else {
					console.log('upload statusCode', res.statusCode)
					uni.showToast({
						title: data.message,
						icon: 'none'
					})

					// 未登录
					if (res.statusCode == 401) {
							uni.navigateTo({
								url: '/pages/user/login-reg'
							})
					}
				}
			},
			fail: (res) => {
				console.log('fail res', res)
				return false;
			},
			complete: (res => {
				showLoading && uni.hideLoading()
			})
		})
	})
}